package com.creating.mict.dao;

import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.creating.mict.common.DateUtils;
import com.creating.mict.domain.PatientRule;
import com.creating.mict.domain.PatientSetting;
import com.creating.mict.domain.XtyRecord;

public class XtyDao extends HibernateDaoSupport {

	private static final Log log = LogFactory.getLog(XtyDao.class);

	/**
	 * 
	* @Title: queryPatientXty 
	* @Description: 获取血糖仪签约患者及其测量结果
	* @param @param fbtime
	* @param @param fetime
	* @param @param fstate
	* @param @param fkeywords
	* @param @return 
	* @return List<XyjRecord>    返回类型 
	* @throws
	 */
	public List<XtyRecord> queryPatientXty(String loginName, String foffice, String fbtime, String fetime, String fstate, String fkeywords, String ftakeBack) {

		String sql = "";
		sql = " select a.fpid, a.fname, a.fsex, a.fphone1, a.fstate, b.fcqxt, b.fchxt1, b.fchxt2, b.fdate, b.frdate, b.fstate_data "
			+ " , c.fcqxt_high, c.fcqxt_low, c.fchxt1_high, c.fchxt1_low, c.fchxt2_high, c.fchxt2_low "
				+ " from tds_patient a, tds_xty_record b, tds_patient_setting c  "
				+ " where a.fphone1=b.fphone and a.fphone1=c.fphone ";

		if (fbtime == null || fbtime.equals("null") || fbtime.equals("")) {
			sql += " and b.frdate <= to_date('" + fetime
					+ " 23:59:59','yyyy-mm-dd hh24:mi:ss') ";
		} else {
			sql += " and b.frdate between to_date('" + fbtime
					+ " 00:00:00','yyyy-mm-dd hh24:mi:ss') and to_date('"
					+ fetime + " 23:59:59','yyyy-mm-dd hh24:mi:ss') ";
		}
		
		//分中心查询
		if(loginName.equals("admin")) {
			//do nothing
		} else {
			sql	+= " and a.foffice='" + foffice + "' ";
		}

		if (fstate.equals("0")) {
			sql += " ";
		} else {
			sql += " and a.fstate='" + fstate + "' ";
		}
		
		//获取当前机构所有人的检测值
		if(ftakeBack != null && (ftakeBack.equals("true") || ftakeBack.equals("1"))) { //取反
			
		//获取当前机构自己签约患者的检测值
		} else {
			if(loginName.equals("admin")) {
				//do nothing
			} else {
				sql	+= " and a.FSIGN_DOCTOR='" + loginName + "' ";
			}
		}

		if (fkeywords == null || fkeywords.equals("null")) {
			// do nothing
		} else {
			sql += " and (a.fname like '" + fkeywords
					+ "%' or a.fname_pym like '" + fkeywords + "%' "
					// + " or a.fjwh like '" + fkeywords + "%' or a.fjwh_pym
					// like '" + fkeywords + "%' "
					+ " or a.fybkh like '" + fkeywords + "%' "
					+ " or a.fphone1 like '" + fkeywords + "%') ";
		}

		sql += " order by b.frdate desc, a.fname asc ";

		Query query = this.getSession().createSQLQuery(sql);
		List list = query.list();
		List<XtyRecord> xr_list = new ArrayList<XtyRecord>();

		String cqxt1 = "";
		String cqxt2 = "";
		String chxt11 = "";
		String chxt12 = "";
		String chxt21 = "";
		String chxt22 = "";
		
		for (int i = 0; i < list.size(); i++) {
			Object[] obj = (Object[]) list.get(i);
			XtyRecord xr = new XtyRecord();
			for (int j = 0; j < obj.length; j++) {
				xr.setFpid("" + obj[0]);
				xr.setFname("" + obj[1]);
				xr.setFsex("" + obj[2]);
				xr.setFphone("" + obj[3]);
				xr.setFstate("" + obj[4]);
				xr.setFcqxt("" + obj[5]);
				xr.setFchxt1("" + obj[6]);
				xr.setFchxt2("" + obj[7]);
				xr.setFdateStr("" + obj[8]);
				xr.setFrdateStr("" + obj[9]);
				
				cqxt1 = "" + obj[11];
				cqxt2 = "" + obj[12];
				chxt11 = "" + obj[13];
				chxt11 = "" + obj[14];
				chxt21 = "" + obj[15];
				chxt21 = "" + obj[16];
				
				boolean boo1 = compareNum(cqxt1, cqxt2, xr.getFcqxt());
				boolean boo2 = compareNum(chxt11, chxt12, xr.getFchxt1());
				boolean boo3 = compareNum(chxt21, chxt22, xr.getFchxt2());
				if(boo1 && boo2 && boo3) {
					xr.setFstate_data("0");
				} else {
					xr.setFstate_data("1");
				}
			}
			xr_list.add(xr);
		}
		return xr_list;
	}


	private boolean compareNum(String v1, String v2, String str) {
		if(v1 == null || v1.equals("null") || v1.equals("")) {
			v1 = "0";
		}
		if(v2 == null || v2.equals("null") || v2.equals("")) {
			v2 = "0";
		}
		if(str == null || str.equals("null") || str.equals("")) {
			str = "0";
		}
		
		if(Double.parseDouble(v2) <= Double.parseDouble(str) && Double.parseDouble(str) <= Double.parseDouble(v1)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 
	 * @Title: produceXtyToChart
	 * @Description: 获取测量数据变化曲线
	 * @param
	 * @param fbtime
	 * @param
	 * @param fetime
	 * @param
	 * @param fphone1
	 * @param
	 * @param fname
	 * @param
	 * @return
	 * @return String 返回类型
	 * @throws
	 */
	public List<XtyRecord> produceXtyToChart0(String fbtime, String fetime,
			String fphone1) {

		String sql = "";
		sql = " select frdate, fcqxt "
				+ " from tds_xty_record  " + " where fphone='" + fphone1 + "' ";

		if (fbtime == null || fbtime.equals("null") || fbtime.equals("")) {
			sql += " and frdate <= to_date('" + fetime
					+ " 23:59:59','yyyy-mm-dd hh24:mi:ss') ";
		} else {
			sql += " and frdate between to_date('" + fbtime
					+ " 00:00:00','yyyy-mm-dd hh24:mi:ss') and to_date('"
					+ fetime + " 23:59:59','yyyy-mm-dd hh24:mi:ss') ";
		}
		sql += " and fcqxt is not null  ";
		sql += " order by frdate asc ";

		Query query = this.getSession().createSQLQuery(sql);
		List list = query.list();
		List<XtyRecord> xr_list = new ArrayList<XtyRecord>();

		
		int total  = 0;
		int count  = 30;
		if(list != null) {
			total = list.size();
		}
		if(total <= 30) {
			count = 0;
		} else {
			count = total - 30;
		}
		
		for (int i = count; i < total; i++) {
				Object[] obj = (Object[]) list.get(i);
				XtyRecord xr = new XtyRecord();
				for (int j = 0; j < obj.length; j++) {
					xr.setFrdateStr("" + obj[0]);
					xr.setFcqxt("" + obj[1]);
				}
				xr_list.add(xr);
		}
		return xr_list;
	}
	
	/**
	 * 
	* @Title: produceXtyToChart0 
	* @Description: 外网查询 
	* @param @param fphone1
	* @param @param limit
	* @param @return 
	* @return List<XtyRecord>    返回类型 
	* @throws
	 */
	public List<XtyRecord> produceXtyToChart0(String fphone1, int limit) {

		String sql = "";
		sql = " select frdate, fcqxt "
				+ " from tds_xty_record  " + " where fphone='" + fphone1 + "' ";

		sql += " and fcqxt is not null  ";
		sql += " order by frdate asc ";

		Query query = this.getSession().createSQLQuery(sql);
		List list = query.list();
		List<XtyRecord> xr_list = new ArrayList<XtyRecord>();
		
		int total  = 0;
		int count  = 0;
		if(list != null) {
			total = list.size();
		}
		if(total <= limit) {
			count = 0;
		} else {
			count = total - limit;
		}
		
		for (int i = count; i < total; i++) {
				Object[] obj = (Object[]) list.get(i);
				XtyRecord xr = new XtyRecord();
				for (int j = 0; j < obj.length; j++) {
					xr.setFrdateStr("" + obj[0]);
					xr.setFcqxt("" + obj[1]);
				}
				xr_list.add(xr);
		}
		return xr_list;
	}

	/**
	 * 
	 * @Title: produceXtyToChart
	 * @Description: 获取测量数据变化曲线
	 * @param
	 * @param fbtime
	 * @param
	 * @param fetime
	 * @param
	 * @param fphone1
	 * @param
	 * @param fname
	 * @param
	 * @return
	 * @return String 返回类型
	 * @throws
	 */
	public List<XtyRecord> produceXtyToChart1(String fbtime, String fetime,
			String fphone1) {

		String sql = "";
		sql = " select frdate, fchxt1 "
				+ " from tds_xty_record  " + " where fphone='" + fphone1 + "' ";

		if (fbtime == null || fbtime.equals("null") || fbtime.equals("")) {
			sql += " and frdate <= to_date('" + fetime
					+ " 23:59:59','yyyy-mm-dd hh24:mi:ss') ";
		} else {
			sql += " and frdate between to_date('" + fbtime
					+ " 00:00:00','yyyy-mm-dd hh24:mi:ss') and to_date('"
					+ fetime + " 23:59:59','yyyy-mm-dd hh24:mi:ss') ";
		}
		sql += " and fchxt1 is not null  ";
		sql += " order by frdate asc ";

		Query query = this.getSession().createSQLQuery(sql);
		List list = query.list();
		List<XtyRecord> xr_list = new ArrayList<XtyRecord>();

		int total  = 0;
		int count  = 30;
		if(list != null) {
			total = list.size();
		}
		if(total <= 30) {
			count = 0;
		} else {
			count = total - 30;
		}
		
		for (int i = count; i < total; i++) {
				Object[] obj = (Object[]) list.get(i);
				XtyRecord xr = new XtyRecord();
				for (int j = 0; j < obj.length; j++) {
					xr.setFrdateStr("" + obj[0]);
					xr.setFchxt1("" + obj[1]);
				}
				xr_list.add(xr);
		}
		return xr_list;
	}
	
	/**
	 * 
	* @Title: produceXtyToChart1 
	* @Description: 外网查询 
	* @param @param fphone1
	* @param @param limit
	* @param @return 
	* @return List<XtyRecord>    返回类型 
	* @throws
	 */
	public List<XtyRecord> produceXtyToChart1(String fphone1, int limit) {

		String sql = "";
		sql = " select frdate, fchxt1 "
			+ " from tds_xty_record  " + " where fphone='" + fphone1 + "' ";

		sql += " and fchxt1 is not null  ";
		sql += " order by frdate asc ";

		Query query = this.getSession().createSQLQuery(sql);
		List list = query.list();
		List<XtyRecord> xr_list = new ArrayList<XtyRecord>();
		
		int total  = 0;
		int count  = 0;
		if(list != null) {
			total = list.size();
		}
		if(total <= limit) {
			count = 0;
		} else {
			count = total - limit;
		}
		
		for (int i = count; i < total; i++) {
				Object[] obj = (Object[]) list.get(i);
				XtyRecord xr = new XtyRecord();
				for (int j = 0; j < obj.length; j++) {
					xr.setFrdateStr("" + obj[0]);
					xr.setFchxt1("" + obj[1]);
				}
				xr_list.add(xr);
		}
		return xr_list;
	}

	/**
	 * 
	 * @Title: produceXtyToChart
	 * @Description: 获取测量数据变化曲线
	 * @param
	 * @param fbtime
	 * @param
	 * @param fetime
	 * @param
	 * @param fphone1
	 * @param
	 * @param fname
	 * @param
	 * @return
	 * @return String 返回类型
	 * @throws
	 */
	public List<XtyRecord> produceXtyToChart2(String fbtime, String fetime,
			String fphone1) {

		String sql = "";
		sql = " select frdate, fchxt2 "
				+ " from tds_xty_record  " + " where fphone='" + fphone1 + "' ";

		if (fbtime == null || fbtime.equals("null") || fbtime.equals("")) {
			sql += " and frdate <= to_date('" + fetime
					+ " 23:59:59','yyyy-mm-dd hh24:mi:ss') ";
		} else {
			sql += " and frdate between to_date('" + fbtime
					+ " 00:00:00','yyyy-mm-dd hh24:mi:ss') and to_date('"
					+ fetime + " 23:59:59','yyyy-mm-dd hh24:mi:ss') ";
		}
		sql += " and fchxt2 is not null  ";
		sql += " order by frdate asc ";

		Query query = this.getSession().createSQLQuery(sql);
		List list = query.list();
		List<XtyRecord> xr_list = new ArrayList<XtyRecord>();

		int total  = 0;
		int count  = 30;
		if(list != null) {
			total = list.size();
		}
		if(total <= 30) {
			count = 0;
		} else {
			count = total - 30;
		}
		
		for (int i = count; i < total; i++) {
				Object[] obj = (Object[]) list.get(i);
				XtyRecord xr = new XtyRecord();
				for (int j = 0; j < obj.length; j++) {
					xr.setFrdateStr("" + obj[0]);
					xr.setFchxt2("" + obj[1]);
				}
				xr_list.add(xr);
		}
		return xr_list;
	}
	
	/**
	 * 
	* @Title: produceXtyToChart2 
	* @Description: 外网查询 
	* @param @param fphone1
	* @param @param limit
	* @param @return 
	* @return List<XtyRecord>    返回类型 
	* @throws
	 */
	public List<XtyRecord> produceXtyToChart2(String fphone1, int limit) {

		String sql = "";
		sql = " select frdate, fchxt2 "
			+ " from tds_xty_record  " + " where fphone='" + fphone1 + "' ";

		sql += " and fchxt2 is not null  ";
		sql += " order by frdate asc ";

		Query query = this.getSession().createSQLQuery(sql);
		List list = query.list();
		List<XtyRecord> xr_list = new ArrayList<XtyRecord>();
		
		int total  = 0;
		int count  = 0;
		if(list != null) {
			total = list.size();
		}
		if(total <= limit) {
			count = 0;
		} else {
			count = total - limit;
		}
		
		for (int i = count; i < total; i++) {
				Object[] obj = (Object[]) list.get(i);
				XtyRecord xr = new XtyRecord();
				for (int j = 0; j < obj.length; j++) {
					xr.setFrdateStr("" + obj[0]);
					xr.setFchxt2("" + obj[1]);
				}
				xr_list.add(xr);
		}
		return xr_list;
	}

	/**
	 * 
	 * @Title: signPatientRule
	 * @Description: 保存患者设置
	 * @param
	 * @param pr
	 * @param
	 * @return
	 * @return boolean 返回类型
	 * @throws
	 */
	public boolean signPatientRule(PatientRule pr) {
		try {
			getHibernateTemplate().saveOrUpdate(pr);
			getHibernateTemplate().flush();
			log.info("保存患者设置成功!");
			return true;
		} catch (DataAccessException e) {
			log.error("保存患者设置失败!");
			return false;
		}
	}

	/**
     * 
    * @Title: saveXtyOfSetting 
    * @Description: 保存血糖设置信息
    * @param @param fphone1
    * @param @param fcqxt_low
    * @param @param fcqxt_high
    * @param @param fchxt1_low
    * @param @param fchxt1_high
    * @param @param fchxt2_low
    * @param @param fchxt2_high
    * @param @return 
    * @return boolean    返回类型 
    * @throws
     */
	public boolean saveXtyOfSetting(String fphone, String fcqxt_low, String fcqxt_high, String fchxt1_low, String fchxt1_high, String fchxt2_low, String fchxt2_high ) {
		try {
			DateUtils dateUtils = new DateUtils();
			String sql = "update tds_patient_setting set "
				       + "fcqxt_low='" + fcqxt_low + "' , "
				       + "fcqxt_high='" + fcqxt_high + "' , "
				       + "fchxt1_low='" + fchxt1_low + "' , "
				       + "fchxt1_high='" + fchxt1_high + "' , "
				       + "fchxt2_low='" + fchxt2_low + "' , "
				       + "fchxt2_high='" + fchxt2_high + "' , "
				       + "fopdate=" + " to_date('"
					   + dateUtils.getCurrentDateTime()
					   + "','YYYY-MM-DD HH24:MI:SS') "
					   + " where fphone='" + fphone + "' ";
			
			Query query = this.getSession().createSQLQuery(sql);
			int num = query.executeUpdate();
			if (num > 0) {
				log.info("保存血糖设置信息成功！");
				return true;
			} else {
				log.error("保存血糖设置信息失败！");
				return false;
			}

		} catch (RuntimeException re) {
			log.error("保存血糖设置信息失败！", re);
			throw re;
		}
	}

	/**
	 * 
	* @Title: getPatientSettingInfoByPhone 
	* @Description: 获取患者设置信息 
	* @param @param fphone
	* @param @return 
	* @return PatientSetting    返回类型 
	* @throws
	 */
	public PatientSetting getPatientSettingInfoByPhone(String fphone) {

		String sql = "";
		sql = " select fphone, fssy_low, fssy_high, fszy_low, fszy_high, fxl_low, fxl_high, fmyc_low, fmyc_high, "
			+ " fcqxt_low, fcqxt_high, fchxt1_low, fchxt1_high, fchxt2_low, fchxt2_high "
			+ " from tds_patient_setting " 
			+ " where fphone='" + fphone + "' "; 
		
		Query query = this.getSession().createSQLQuery(sql);
		List list = query.list();
		
		PatientSetting ps = new PatientSetting();
		if(list.size() <= 0) {
			return null;
		}
		for (int i = 0; i < list.size(); i++) {
			Object[] obj = (Object[]) list.get(i);
			for (int j = 0; j < obj.length; j++) {
				ps.setFcqxt_low("" + obj[9]);
				ps.setFcqxt_high("" + obj[10]);
				ps.setFchxt1_low("" + obj[11]);
				ps.setFchxt1_high("" + obj[12]);
				ps.setFchxt2_low("" + obj[13]);
				ps.setFchxt2_high("" + obj[14]);
			}
		}
		return ps;
	}
	

}
